package com.woniu.p2p.realms;

import com.woniu.p2p.entity.Admin;
import com.woniu.p2p.service.AdminService;
import com.woniu.p2p.service.RoleService;
import com.woniu.p2p.vo.RoleVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RoleService roleService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Admin principal = (Admin)principalCollection.getPrimaryPrincipal();
        Set<String> roleMap = new HashSet<>();
        List<RoleVo> roles = roleService.findAllByAdminId(principal.getAdminId());
        for (RoleVo role:roles){
            roleMap.add(role.getRoleName());
        }
        return new SimpleAuthorizationInfo(roleMap);
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String adminName = (String)token.getPrincipal();
        Admin admin = adminService.login(adminName);
        if(admin == null){
            throw new UnknownAccountException("unknownAccount");
        }
        ByteSource bytes = ByteSource.Util.bytes(adminName);
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(admin, admin.getAdminPassword(), bytes, this.getName());
        SecurityUtils.getSubject().getSession().setAttribute("userInfo",admin);
        String getimgbyadminaccount = adminService.getimgbyadminaccount(adminName);
        SecurityUtils.getSubject().getSession().setAttribute("head",getimgbyadminaccount);
        return info;
    }

}
